package com.laijiale.component;

import com.laijiale.exception.ServiceException;
import com.laijiale.result.Result;
import com.laijiale.result.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Objects;

/**
 * @author laijiale
 * @date 2024年12月22日 12:00
 */
@Slf4j
@RestControllerAdvice(basePackages = {"com.laijiale"})
public class ExceptionAdvice {
    @ExceptionHandler(ServiceException.class)
    public Object serviceException(ServiceException e){
        log.error("业务异常"+e.getMessage());
        return new Result<>(ResultCode.FAILED,e.getMessage());
    }

    public Object methodArgumentNotValidException(Exception e){
        //获取BindingResult
        BindingResult bindingResult;
        if (e instanceof MethodArgumentNotValidException){
            bindingResult =((MethodArgumentNotValidException) e).getBindingResult();
        }else{
            bindingResult=((BindException)e).getBindingResult();
        }
        //获取BindingResult中所有属性错误信息集合中的第一个属性错误
        FieldError firstFieldError =bindingResult.getFieldErrors().get(0);
        //异常信息："xxx实例的xxx属性校验失败：xxx异常信息”
        String message=String.format("%s实例的%s属性校验失败：%s",firstFieldError.getObjectName(),
                firstFieldError.getField(),firstFieldError.getDefaultMessage());
        log.error(message);
        return new Result<>(ResultCode.VALIDATE_FAILED,message);
    }
    @ExceptionHandler(Exception.class)
    public Object exception(Exception e){
        log.error("其他异常："+e.getMessage());
        return new Result<>(ResultCode.FAILED,e.getMessage());
    }

}

